package com.leyou.order.service.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.auth.inter.pojo.UserInfo;
import com.leyou.common.bean.PageResult;
import com.leyou.common.bean.Result;
import com.leyou.common.bean.ResultCode;
import com.leyou.common.util.IdWorker;
import com.leyou.common.util.StringUtil;
import com.leyou.order.inter.dto.OrderPageDTO;
import com.leyou.order.inter.dto.WebOrderPageDTO;
import com.leyou.order.inter.pojo.Order;
import com.leyou.order.inter.pojo.OrderDetail;
import com.leyou.order.inter.pojo.OrderStatus;
import com.leyou.order.service.config.IdWorkerProperties;
import com.leyou.order.service.interceptor.LoginInterceptor;
import com.leyou.order.service.mapper.OrderDetailMapper;
import com.leyou.order.service.mapper.OrderMapper;
import com.leyou.order.service.mapper.OrderStatusMapper;
import com.leyou.order.service.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zqq
 * @ClassName OrderService
 * @Description
 * @date 2020/3/10-16:41
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private IdWorkerProperties idWorker;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper detailMapper;

    @Autowired
    private OrderStatusMapper statusMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Override
    @Transactional
    public Result<String> createOrder(Order order) {
        // 生成orderId
        Long orderId = new IdWorker(idWorker.getWorkerId(),idWorker.getDatacenterId()).nextId();
        // 获取登录用户
        UserInfo user = LoginInterceptor.getLoginUser();
        // 初始化数据
        order.setBuyerNick(user.getUsername());
        order.setBuyerRate(false);
        order.setCreateTime(new Date());
        order.setOrderId(orderId);
        order.setUserId(user.getId());

        // 保存订单状态
        OrderStatus orderStatus = new OrderStatus();
        orderStatus.setOrderId(orderId);
        orderStatus.setCreateTime(order.getCreateTime());
        orderStatus.setStatus(1);// 初始状态为未付款

        // 订单详情中添加orderId
        order.getOrderDetails().forEach(od -> od.setOrderId(orderId));

        // 保存数据
        try {
            int count = this.orderMapper.insertSelective(order);
            if(count == 0){
                return Result.newFailure(ResultCode.ORDER_INSERT_FAIL);
            }
            this.statusMapper.insertSelective(orderStatus);
            this.detailMapper.insertList(order.getOrderDetails());
        } catch (Exception e) {
            log.error("sql异常", e);
            return Result.newFailure(ResultCode.S_SYSTEM_EXCEPTION);
        }
        log.info("生成订单，订单编号：{}，用户id：{}", orderId, user.getId());
        Map<String,Object> map = new HashMap<>();
        map.put("userId",user.getId());
        map.put("detail",order.getOrderDetails());
        this.amqpTemplate.convertAndSend("leyou.cart.exchange", "cart.clear", map);
        return Result.newSuccess(orderId.toString());
    }

    @Override
    public Result<Order> queryById(Long id) {
        // 查询订单
        Order order = null;
        try {
            order = this.orderMapper.selectByPrimaryKey(id);
        } catch (Exception e) {
            log.error("sql异常", e);
            return Result.newFailure(ResultCode.S_SYSTEM_EXCEPTION);
        }
        if(order == null){
            return Result.newFailure(ResultCode.ORDER_NULL_FAIL);
        }

        // 查询订单详情
        OrderDetail detail = new OrderDetail();
        detail.setOrderId(id);
        List<OrderDetail> details = null;
        try {
            details = this.detailMapper.select(detail);
        } catch (Exception e) {
            log.error("sql异常", e);
            return Result.newFailure(ResultCode.S_SYSTEM_EXCEPTION);
        }
        if(details == null || details.size() == 0){
            return Result.newFailure(ResultCode.S_SYSTEM_DATA_EXCEPTION);
        }
        order.setOrderDetails(details);

        // 查询订单状态
        OrderStatus status = null;
        try {
            status = this.statusMapper.selectByPrimaryKey(order.getOrderId());
        } catch (Exception e) {
            log.error("sql异常", e);
            return Result.newFailure(ResultCode.S_SYSTEM_EXCEPTION);
        }
        if(status == null ){
            return Result.newFailure(ResultCode.S_SYSTEM_DATA_EXCEPTION);
        }
        order.setStatus(status.getStatus());
        return Result.newSuccess(order);
    }

    @Override
    public Result<PageResult<Order>> queryUserOrderList(OrderPageDTO dto) {
        // 分页
        PageHelper.startPage(dto.getPage(), dto.getRows());
        // 获取登录用户
        UserInfo user = LoginInterceptor.getLoginUser();
        // 创建查询条件
        List<Order>  orders = null;
        try {
            orders = this.orderMapper.queryOrderList(user.getId(), dto.getStatus());
        } catch (Exception e) {
            log.error("sql异常", e);
            return Result.newFailure(ResultCode.S_SYSTEM_EXCEPTION);
        }
        for (Order order : orders) {
            List<OrderDetail> orderDetails = this.detailMapper.select(new OrderDetail(order.getOrderId()));
            if(orderDetails.size() > 0)
                order.setOrderDetails(orderDetails);
            OrderStatus orderStatus = this.statusMapper.selectByPrimaryKey(order.getOrderId());
            order.setOrderStatus(orderStatus);
        }
        PageInfo<Order> pageInfo = new PageInfo<>(orders);
        PageResult<Order> result = new PageResult<>(pageInfo.getTotal(),pageInfo.getPages(), orders);
        return Result.newSuccess(result);
    }

    @Override
    @Transactional
    public Result updateStatus(Long id, Integer status) {
        OrderStatus record = new OrderStatus();
        record.setOrderId(id);
        record.setStatus(status);
        // 根据状态判断要修改的时间
        switch (status) {
            case 2:
                record.setPaymentTime(new Date());// 付款
                this.amqpTemplate.convertAndSend("leyou.statis.exchange", "statis.insert", id);
                break;
            case 3:
                record.setConsignTime(new Date());// 发货
                break;
            case 4:
                record.setEndTime(new Date());// 确认收获，订单结束
                break;
            case 5:
                record.setCloseTime(new Date());// 交易失败，订单关闭
                break;
            case 6:
                record.setCommentTime(new Date());// 评价时间
                break;
            default:
                return null;
        }
        try {
            int count = this.statusMapper.updateByPrimaryKeySelective(record);
            if(count != 1){
                return Result.newFailure(ResultCode.ORDER_UPDATE_FAIL);
            }
        } catch (Exception e) {
            log.error("sql异常", e);
            return Result.newFailure(ResultCode.S_SYSTEM_EXCEPTION);
        }
        return Result.newSuccess();
    }

    @Override
    public Result<List<OrderDetail>> queryDetailByOrderId(Long orderId) {
        OrderDetail detail = new OrderDetail();
        detail.setOrderId(orderId);
        List<OrderDetail> detailList = null;
        try {
            detailList = this.detailMapper.select(detail);
        } catch (Exception e) {
            log.error("sql异常", e);
            return Result.newFailure(ResultCode.S_SYSTEM_EXCEPTION);
        }
        return Result.newSuccess(detailList);
    }

    @Override
    public Result<PageResult<Order>> queryOrderByDto(WebOrderPageDTO dto) {
        // 分页
        PageHelper.startPage(dto.getPage(), dto.getRows());
        // 创建查询条件
        List<Order>  orders = null;
        try {
            orders = this.orderMapper.selectOrderByDto(dto);
        } catch (Exception e) {
            log.error("sql异常", e);
            return Result.newFailure(ResultCode.S_SYSTEM_EXCEPTION);
        }
        PageInfo<Order> pageInfo = new PageInfo<>(orders);
        PageResult<Order> result = new PageResult<>(pageInfo.getTotal(),pageInfo.getPages(), orders);
        return Result.newSuccess(result);
    }

    @Override
    public Result deleteOrder(String ids) {
        String[] orderIds = ids.split(",");
        for (String orderId : orderIds) {
            if(StringUtil.isEmpty(orderId)){
                Long id = Long.parseLong(orderId);
                try {
                    this.orderMapper.deleteByPrimaryKey(id);
                    this.statusMapper.deleteByPrimaryKey(id);
                    OrderDetail detail = new OrderDetail();
                    detail.setOrderId(id);
                    this.detailMapper.delete(detail);
                } catch (Exception e) {
                    log.error("sql异常", e);
                    return Result.newFailure(ResultCode.S_SYSTEM_EXCEPTION);
                }
            }
        }
        return Result.newSuccess();
    }
}
